package com.qianxx.viewlibrary.text.autotextview;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Camera;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.TextSwitcher;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;

import com.qianxx.viewlibrary.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 字幕公告栏（上下翻滚）
 */
public class AutoTextView extends TextSwitcher implements ViewFactory {
    private Context context;
    //mInUp,mOutUp分别构成向上翻页的进出动画
    private Rotate3dAnimation inUp;
    private Rotate3dAnimation outUp;

    //mInDown,mOutDown分别构成向下翻页的进出动画
    private Rotate3dAnimation inDown;
    private Rotate3dAnimation outDown;

    private float textSize;
    private int textColor;
    private int maxLines;

    private static final int FLAG = 0x01;
    private int pos = 0;
    private List<String> list = new ArrayList<>();
    private Resources res;
    private DisplayMetrics dm;

    private OnItemClickListener onItemClickListener;

    public AutoTextView(Context context) {
        this(context, null);
    }

    public AutoTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.auto3d);
        textSize = a.getDimension(R.styleable.auto3d_auto_textSize, 16);
        textColor = a.getColor(R.styleable.auto3d_auto_textColor, Color.BLACK);
        maxLines = a.getInteger(R.styleable.auto3d_maxLines, 1);
        a.recycle();
        this.res = context.getResources();
        dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getMetrics(dm);
        init();
    }

    private void init() {
        setFactory(this);
    }

    private Rotate3dAnimation createAnim(float start, float end, boolean turnIn, boolean turnUp) {
        final Rotate3dAnimation rotation = new Rotate3dAnimation(start, end, turnIn, turnUp);
        rotation.setDuration(300);
        rotation.setFillAfter(false);
        rotation.setInterpolator(new AccelerateInterpolator());
        return rotation;
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public int sp2px(float spValue) {
        final float fontScale = res.getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    private int dip2px(float dpValue) {
        return (int) (dpValue * dm.density + 0.5f);
    }

    //这里返回的TextView，就是我们看到的View
    @Override
    public View makeView() {
        TextView t = (TextView) LayoutInflater.from(context).inflate(R.layout.auto_textview, null);
        t.setMaxLines(maxLines);
        t.setTextColor(textColor);
        t.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(v);
                }
            }
        });
        return t;
    }

    //定义动作，向下滚动翻页
    public void previous() {
        if (getInAnimation() != inDown) {
            setInAnimation(inDown);
        }
        if (getOutAnimation() != outDown) {
            setOutAnimation(outDown);
        }
    }

    //定义动作，向上滚动翻页
    public void next() {
        if (getInAnimation() != inUp) {
            setInAnimation(inUp);
        }
        if (getOutAnimation() != outUp) {
            setOutAnimation(outUp);
        }
    }

    class Rotate3dAnimation extends Animation {
        private final float mFromDegrees;
        private final float mToDegrees;
        private final boolean mTurnIn;
        private final boolean mTurnUp;
        private float mCenterX;
        private float mCenterY;
        private Camera mCamera;

        public Rotate3dAnimation(float fromDegrees, float toDegrees, boolean turnIn, boolean turnUp) {
            mFromDegrees = fromDegrees;
            mToDegrees = toDegrees;
            mTurnIn = turnIn;
            mTurnUp = turnUp;
        }

        @Override
        public void initialize(int width, int height, int parentWidth, int parentHeight) {
            super.initialize(width, height, parentWidth, parentHeight);
            mCamera = new Camera();
            mCenterY = getHeight() / 2;
            mCenterX = getWidth() / 2;
        }

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            final float fromDegrees = mFromDegrees;
            float degrees = fromDegrees + ((mToDegrees - fromDegrees) * interpolatedTime);

            final float centerX = mCenterX;
            final float centerY = mCenterY;
            final Camera camera = mCamera;
            final int derection = mTurnUp ? 1 : -1;

            final Matrix matrix = t.getMatrix();

            camera.save();
            if (mTurnIn) {
                camera.translate(0.0f, derection * mCenterY * (interpolatedTime - 1.0f), 0.0f);
            } else {
                camera.translate(0.0f, derection * mCenterY * (interpolatedTime), 0.0f);
            }
            camera.rotateX(degrees);
            camera.getMatrix(matrix);
            camera.restore();

            matrix.preTranslate(-centerX, -centerY);
            matrix.postTranslate(centerX, centerY);
        }
    }

    public void setTextList(List<String> list) {
        this.list = list;
        //setText(list.get(0));
        inUp = createAnim(-90, 0, true, true);
        outUp = createAnim(0, 90, false, true);
        inDown = createAnim(90, 0, true, false);
        outDown = createAnim(0, -90, false, false);
        //TextSwitcher主要用于文件切换，比如 从文字A 切换到 文字 B，
        //setInAnimation()后，A将执行inAnimation，
        //setOutAnimation()后，B将执行OutAnimation
        setInAnimation(inUp);
        setOutAnimation(outUp);
        handler.sendEmptyMessage(FLAG);
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (list.size() > 0) {
                        pos = pos % list.size();
                        next();
                        setText(list.get(pos));
                        pos++;
                        handler.sendEmptyMessageDelayed(FLAG, 2000);
                    }
                    break;
            }
        }
    };

    public interface OnItemClickListener {
        void onItemClick(View v);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }
}